<template>
  <div class="content">
    <div class="ship-content">
      <div class="top-wrap">
        <div>常规下单</div>
        <div></div>
      </div>
      <div class="address-wrap">
        <div class="left">
          <SendEditInfo :sendForm="getSendForm" :companyName="selectedCompany"
            @updateCompany="selectedCompany = $event">
            <template v-slot:default>
              <i class="iconfont">&#xe604;</i>
            </template>
          </SendEditInfo>
        </div>
        <div class="right">
          <ReceiveEditInfo :ReceiveForm="getReceiveForm" :companyName="selectedCompany"
            @updateCompany="selectedCompany = $event">
            <template v-slot:default>
              <i class="iconfont">&#xe603;</i>
            </template>
          </ReceiveEditInfo>
        </div>
      </div>
      <div class="express-way">
        <div class="title">寄件方式</div>
        <div class="way">
          <div>
            <el-radio-group v-model="sendWay">
              <el-radio label="预约上门取件" size="large" border>预约上门取件</el-radio>
              <el-radio label="自行联系快递员" size="large" border>自行联系快递员</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div class="time" v-if="sendWay === '预约上门取件'">
          <div class="block">
            <div>
              <el-icon>
                <Calendar />
              </el-icon>
            </div>

            <span>期望上门时间</span>
            <el-date-picker v-model="wishTime" type="datetime" placeholder="请选择上门时间" format="YYYY-MM-DD HH:mm:ss"
              date-format="MMM DD, YYYY" time-format="HH:mm" />
          </div>
        </div>
        <div class="time" v-else>
          <div class="block">
            <div></div><span></span>
          </div>
        </div>
      </div>
      <div class="object-info">
        <div class="objcet-title">
          <div>物品信息</div>
        </div>
        <div class="object-name">
          <div>物品名称:</div>
          <div>
            <el-input id="objectname" v-model="objectName" placeholder="请输入物品名称" />
          </div>
        </div>
        <div class="total-weight">
          <div class="predict-weight">
            <div>
              <div>预估总重量(kg):</div>
              <div>
                <el-input-number v-model="totalWeight" :min="1" :max="10" @change="handleChange" />
              </div>
            </div>
          </div>
          <div class="num">
            <div>
              <div>件数(件):</div>
              <div>
                <el-input-number v-model="totalPieces" :min="1" :max="10" @change="handleChange" />
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="pay-way">
        <div>付款方式</div>
        <div>
          <el-radio-group v-model="payWay">
            <el-radio label="寄付现结" size="large" border>寄付现结</el-radio>
            <el-radio label="到付后结" size="large" border>到付后结</el-radio>
          </el-radio-group>
        </div>
      </div>
    </div>
    <div class="pay">
      <div>
        <div>
          <div>预估总价:</div>
          <div>100元</div>
        </div>
      </div>
      <div>
        <div>
          <el-checkbox v-model="checked" label="阅读并同意相关条款" size="large" />
        </div>
        <div>
          <el-button color="red" @click="orderNow"> 立即下单</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import SendEditInfo from "@/components/SendEditInfo.vue";
import ReceiveEditInfo from "@/components/ReceiveEditInfo.vue";
import { Calendar } from "@element-plus/icons-vue";
import { useAuthStore } from "@/store/userInfo";
import { ref, reactive, nextTick } from "vue";
import { useRouter } from 'vue-router';
import axios from "axios";
import { ElNotification, ElLoading } from "element-plus";
const authStore = useAuthStore();
const router = useRouter();
const selectedCompany = ref('');
let sendWrap = reactive({
  name: "",
  phoneNumber: " ",
  province: " ",
  address: " ",
  companyName: " ",
});
let receiveWrap = reactive({
  name: "",
  phoneNumber: " ",
  province: " ",
  address: " ",
  companyName: " ",
});
interface FormData {
  name: string;
  phoneNumber: string;
  province: string;
  address: string;
  companyName: string;
}
function getSendForm(form: FormData) {
  sendWrap.name = form.name;
  sendWrap.phoneNumber = form.phoneNumber;
  sendWrap.province = form.province;
  sendWrap.address = form.address;
  sendWrap.companyName = form.companyName;
  console.log("sendWarp==", sendWrap);
}
function getReceiveForm(form: FormData) {
  receiveWrap.name = form.name;
  receiveWrap.phoneNumber = form.phoneNumber;
  receiveWrap.province = form.province;
  receiveWrap.address = form.address;
  receiveWrap.companyName = form.companyName;
  console.log("receiveWrap==", receiveWrap);
}

const sendWay = ref("预约上门取件");
const payWay = ref("寄付现结");
const wishTime = ref("");
const objectName = ref("");
const totalWeight = ref(1);
const totalPieces = ref(1);
const wrap = reactive({
  send_wrap: sendWrap,
  receive_wrap: receiveWrap,
  send_way: sendWay,
  payway: payWay,
  wish_time: wishTime,
  object_name: objectName,
  total_weight: totalWeight,
  total_pieces: totalPieces,
});
const RouteDTO = reactive({
  userId: -1,
  start: '',
  end: ''
})

const checked = ref(true);

const geoCoder = () => {

}


const orderNow = async () => {
  if (!validateOrderForm(wrap)) {
    return;
  }
  // 显示加载遮罩
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在下单，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  console.log("wrap =", wrap);
  RouteDTO.userId = authStore.userId;
  RouteDTO.start = wrap.send_wrap.address;
  RouteDTO.end = wrap.receive_wrap.address;
  await axios.post("http://localhost:8083/route/insertRoute", RouteDTO)
    .then((response) => {
      console.log("insertRoute Response from server:", response.data);
    })
    .catch((error) => {
      console.error("Error sending data to server:", error);
    })

  await axios
    .post("http://localhost:8085/order/orderNow", wrap)
    .then((response) => {
      console.log("orderNow Response from server:", response.data);
      const orderId = response.data.orderId;
      ElNotification.success({
        title: "Success",
        message: "下单成功！",
        offset: 100,
      });
      nextTick(() => {
        setTimeout(() => {
          // 关闭加载遮罩
          loadingInstance.close();
          // 使用router.push进行页面跳转
          router.push({ path: '/ship/check', query: { orderId } });
        }, 1000); // 延时2000毫秒（2秒）后跳转
      });
    })
    .catch((error) => {
      console.error("Error sending data to server:", error);
      // 关闭加载遮罩
      loadingInstance.close();
      ElNotification.error({
        title: "error",
        message: "下单失败，请稍后再试!",
        offset: 100,
      });
    });
};
const handleChange = (value: number) => {
  console.log(value);
};

function validateOrderForm(wrap: any) {
  // 检查基本信息是否填写
  const isBasicInfoFilled =
    wrap.send_wrap.name &&
    wrap.send_wrap.phoneNumber &&
    wrap.send_wrap.province &&
    wrap.send_wrap.address &&
    wrap.send_wrap.companyName &&
    wrap.receive_wrap.name &&
    wrap.receive_wrap.phoneNumber &&
    wrap.receive_wrap.province &&
    wrap.receive_wrap.address &&
    wrap.receive_wrap.companyName;

  // 检查寄件方式、付款方式、期望上门时间、物品名称、总重量和件数是否填写
  const isDetailsFilled =
    wrap.send_way &&
    wrap.payway &&
    wrap.wish_time &&
    wrap.object_name &&
    wrap.total_weight > 0 &&
    wrap.total_pieces > 0;

  // 如果所有条件都满足，则返回true，否则返回false
  if (isBasicInfoFilled && isDetailsFilled) {
    return true;
  } else {
    ElNotification.error({
      title: "错误",
      message: "请填写所有必填项后再下单",
      offset: 100,
    });
    return false;
  }
}
</script>

<style scoped lang="less">
@font-face {
  font-family: "iconfont";
  /* Project id 4410292 */
  src: url("//at.alicdn.com/t/c/font_4410292_0pr074erb58d.woff2?t=1706444958188") format("woff2"),
    url("//at.alicdn.com/t/c/font_4410292_0pr074erb58d.woff?t=1706444958188") format("woff"),
    url("//at.alicdn.com/t/c/font_4410292_0pr074erb58d.ttf?t=1706444958188") format("truetype");
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 2.5rem;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -webkit-text-stroke-width: 0.2px;
  -moz-osx-font-smoothing: grayscale;
}

.content {
  position: absolute;
  width: 150vh;
  height: 82vh;
  background-color: #eff1f4;
  margin: 1.5vh 0 0 0;
  right: 1vw;
  overflow-y: scroll;

}

.content .ship-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 125vh;
  width: 100%;

  .top-wrap {
    flex: 1;
    background-color: white;
    width: 95%;
    display: flex;
    justify-content: space-between;
    align-items: center;

    >div:first-child {
      width: 12%;
      height: 70%;
      background: linear-gradient(90deg, #523516 0%, #181c17 100%);
      margin-left: 1rem;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #ffe5b1;
    }

    >div:nth-child(2) {
      width: 12%;

      height: 70%;
      margin-right: 1rem;
    }
  }

  .address-wrap {
    flex: 6;
    display: flex;
    align-items: center;
    width: 97%;
    .left {
      flex: 1;
      height: 90%;
      padding: 2px 1rem 2px 1rem;
    }

    .right {
      flex: 1;
      height: 90%;
      padding: 2px 1rem 2px 1rem;
    }
  }



  .object-info {
    flex: 4;
    background-color: white;
    width: 95%;
    border-radius: 1rem;
    padding: 1rem 1rem 1rem 1rem;
    // margin-left: 1rem;
    margin-top: 1rem;
    display: flex;
    flex-direction: column;

    .objcet-title {
      flex: 1;

      display: flex;
      align-items: center;

      >div {
        height: 80%;
        width: 20%;

        display: flex;
        align-items: center;
        margin-left: 1.5rem;
        font-weight: bold;
      }
    }

    .object-name {
      flex: 1;

      display: flex;
      flex-direction: column;

      >div:first-child {
        flex: 1;
        display: flex;
        align-items: center;
        font-size: 0.8rem;
        margin-left: 1.7rem;
      }

      >div:nth-child(2) {
        flex: 1;
        width: 40%;
        margin-left: 1.5rem;
      }

      :deep(.el-input__wrapper) {
        background-color: #f4f5f7 !important;
        box-shadow: 0 0 0 !important;
      }
    }

    .total-weight {
      flex: 2;

      display: flex;

      .predict-weight {
        width: 21%;
        font-size: 0.9em;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        >div {
          width: 100%;
          height: 80%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;

          >div:first-child {
            flex: 1;
            display: flex;
            align-items: center;

            width: 55%;
          }

          >div:nth-child(2) {
            flex: 2;
          }
        }
      }

      .num {
        width: 21%;
        font-size: 0.9em;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        >div {
          width: 100%;
          height: 80%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;

          >div:first-child {
            flex: 1;
            display: flex;
            align-items: center;
            width: 55%;
          }

          >div:nth-child(2) {
            flex: 2;
          }
        }
      }
    }
  }

  .pay-way {
    flex: 1.8;
    background-color: white;
    border-radius: 1rem;
    width: 95%;
    padding: 1rem 1rem 1rem 1rem;
    margin-top: 1rem;
  
    margin-bottom: 1rem;
    display: flex;
    flex-direction: column;

    >div:first-child {
      flex: 1;
      width: 10%;

      display: flex;
      justify-content: center;
      align-items: center;
      font-weight: bold;
    }

    >div:nth-child(2) {
      width: 30%;
      flex: 2;

      display: flex;
      align-items: center;
      margin-left: 1rem;
    }
  }

  .express-way {
    display: flex;
    flex: 2;
    flex-direction: column;
    background-color: white;
    padding: 1rem 1rem 1rem 1rem;
   
    border-radius: 1rem;
    width: 95%;

    .title {
      flex: 1.5;
      box-shadow: none;
      display: flex;
      width: 30%;
      margin-left: 1.5rem;
      align-items: center;
      font-weight: bold;
    }

    .way {
      flex: 2;

      display: flex;
      flex-direction: column;
      justify-content: center;

      :deep(.is-bordered) {
        border: red !important;
      }

      >div:first-child {
        height: 90%;
        width: 40%;

        display: flex;
        align-items: center;

        .el-radio-group {
          margin-left: 2rem;
        }
      }
    }

    .time {
      flex: 1;

      .block {
        width: 35%;
        background-color: #f4f5f7;
        margin-left: 2rem;
        font-size: 0.9rem;
        display: flex;
        justify-content: space-between;

        :deep(.el-input__wrapper) {
          background-color: #f4f5f7 !important;
          box-shadow: 0 0 0 !important;
        }

        >div:first-child {
          display: flex;
          justify-content: center;
          align-items: center;
          padding-left: 0.6rem;
        }

        span {
          flex: 1;
          font-weight: 400;
          display: flex;
          padding-left: 0.4rem;
          align-items: center;
        }
      }
    }
  }
}

.content .pay {
  z-index: 100;
  position: sticky;
  bottom: 1px;
  height: 10%;
  background-color: white;
  width: 95%;
  margin: 0 auto;
  border-radius: 1rem;
  display: flex;

  >div:first-child {
    height: 100%;
    flex: 3;

    display: flex;

    >div {
      width: 40%;

      display: flex;

      >div:first-child {
        flex: 1;

        display: flex;
        justify-content: center;
        align-items: center;
        font-weight: bold;
      }

      >div:nth-child(2) {
        flex: 1;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        color: red;
        font-weight: bolder;
      }
    }
  }

  >div:nth-child(2) {
    flex: 1.5;
    display: flex;

    >div:first-child {
      flex: 1;
      background-color: white;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    >div:nth-child(2) {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
    }

  }
}

.content .ship-content .express-way .way > div:first-child .el-radio-group[data-v-baf8b271] {
    margin-left: 2.6%;
}
.content .ship-content .express-way .time .block[data-v-baf8b271] {
    margin-left: 2%;
}
</style>
